package com.coolingme.controller.config;

import com.coolingme.domain.entity.SecurityUser;
import com.coolingme.service.SecurityService;
import com.coolingme.service.UserService;
import com.coolingme.util.ResponseUtil;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Set;

/**
 * 提供Security权限管理相关请求
 *
 * @author wangyue
 * @date 2020/7/28 14:36
 */
@ApiResponses({@ApiResponse(code = 200, message = "success"),
        @ApiResponse(code = 401, message = "Authentication Failure"),
        @ApiResponse(code = 402, message = "Login Information Invalid"),
        @ApiResponse(code = 403, message = "No Permission"), @ApiResponse(code = 420, message = "Data Error"),
        @ApiResponse(code = 421, message = "Cache Error"), @ApiResponse(code = 500, message = "Request fail")})
@Api(tags = "Security权限管理相关请求")
@ApiSupport(order = 1, author = "wangyue")
@RestController
@RequestMapping("/config/security")
public class SecurityController {

    @Autowired
    private SecurityService securityService;

    @Autowired
    private UserService userService;

    /**
     * 重置redis权限信息
     */
    @GetMapping("/reset")
    public String resetSecurityInRedis(@ApiIgnore @AuthenticationPrincipal SecurityUser securityUser) {
        // 这里先粗糙的设置ROLE_ADMIN角色才可以访问
        Set<String> roles = userService.getRoles(securityUser);
        boolean contains = roles.contains("ROLE_ADMIN");
        if (!contains) {
            return ResponseUtil.success("No Permission");
        }

        Boolean isSuccess = securityService.resetSecurityInRedis();
        if (isSuccess) {
            return ResponseUtil.success("Reset Success");
        } else {
            return ResponseUtil.success("Rest Fail");
        }
    }

}
